package com.czxy.blogs.manage.web.config;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

public class WebInitializer implements WebApplicationInitializer {
		//类或方法
//			AnnotationConfigWebApplicationContext	WEB环境下spring工厂
//			servletContext.addFilter(name , Class)	添加过滤器，等效<filter>
//			servletContext.addServlet(name , Class)	添加servlet，等效<servlet>
	
		//过滤器相关方法 ServletRegistration.Dynamic
//			addMapping(urlPatterns)	追加过滤路径
//			setLoadOnStartup(int)	设置启动顺序

	
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		AnnotationConfigWebApplicationContext application = new AnnotationConfigWebApplicationContext();
		application.register(SpringConfiguration.class);  
		application.register(MyBatisConfiguration.class);
		application.register(MVCConfiguration.class);
		application.setServletContext(servletContext);
		
		FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("CharacterEncodingFilter", new CharacterEncodingFilter("UTF-8"));  
		encodingFilter.addMappingForUrlPatterns(null, true, "/*");

		ServletRegistration.Dynamic springMvcServlet = servletContext.addServlet("springmvc", new DispatcherServlet(application));
		springMvcServlet.addMapping("*.action");
		springMvcServlet.setLoadOnStartup(2);
	}
}
